package top.sdwu_top.kbase.common.interceptor;

import org.springframework.core.MethodParameter;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import top.sdwu_top.kbase.common.annocation.CurrentUser;
import top.sdwu_top.kbase.common.aspect.exception.MyException;
import top.sdwu_top.kbase.entity.KbaseAuthUser;

@Component
public class CurrentUserResolver implements HandlerMethodArgumentResolver {


    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //如果参数类型是User并且有CurrentUser注解则支持
        if (parameter.getParameterType().isAssignableFrom(KbaseAuthUser.class)
                && parameter.hasParameterAnnotation(CurrentUser.class)) {
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        //取出鉴权时存入的登录用户Id
        //String token = webRequest.getHeader(TokenConstants.AUTHORIZATION);
        KbaseAuthUser user = (KbaseAuthUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        //验证token
        //User user = CacheFacade.getObject(TokenConstants.TOKEN_PREFIX + token, new TypeReference<User>(){});
        //jwtTokenStore.readAuthentication(((OAuth2AuthenticationDetails)SecurityContextHolder.getContext().getAuthentication().getDetails()).getTokenValue())
        if (user != null) {
            //从数据库中查询并返回
            return user;
        }
        throw new MyException(403, "未登录");
    }
}